/**
 * Created by Administrator on 2015/10/10.
 */
var appBackService = angular.module('app.backservice', ['ionic', 'ngCordova', 'app.factory']);
var tableCount = 0;
var JsonString = '';
appBackService.factory('BackThread', function ($rootScope,$interval, $http, $cordovaToast, DB, DB_CONFIG) {

  //回调函数
  var callback = function (table, out) {
    if (out && out.length > 0) {
      deleteValueJsonString(table,out,'id');
      JsonString += '{';
      JsonString += 'tablename:' + table + ',';
      JsonString += 'rows:[' + JSON.stringify(out) + ']';
      JsonString += '},';
      if (tableCount == 0 && '' != JsonString) {
        JsonString = '[' + JsonString + '';
        JsonString = JsonString.slice(0, JsonString.length - 2);
        JsonString += JsonString + ']';
        //$cordovaToast.showLongCenter('web服务发送数据结构：'+JsonString);
        webHttp('', JsonString);
      }
    }
  };
  //剔除Json串中的无用字段
  var ids = [];
  var sqls = [];
  var deleteValueJsonString = function(table,JsonString,value){
    //$cordovaToast.showLongTop('删除指定值前的Json：'+JsonString);
    //var ids = [];
    for ( var i = 0; i < JsonString.length; i++){
      ids.push('"'+JsonString[i][value]+'"');
      delete JsonString[i][value];
    }
    var sql = 'update '+table+' set dr=1 where id in ('+ids.join(',')+');';
    sqls.push(sql);

    //$cordovaToast.showLongCenter('删除指定值后的Json：'+JsonString);
    //$cordovaToast.showLongBottom('删除指定值前的Json：'+ids);
  }
  //远程数据访问
  var webHttp = function (url, param) {
    $http.get({
      method: 'POST',
      url: url,
      params: {
        json: param
      }
    })
      .success(function (data, status, headers, config) {
        $cordovaToast.showShortCenter('数据同步成功。。。');
        DB.executeSql(sqls.join(','),[],null);//数据更新，修改标记
        tableCount = 0;
        JsonString = '';
        sqls = [];
        ids = [];
      })
      .error(function (data, status, headers, config) {
        $cordovaToast.showShortCenter('数据同步失败。。。');
        //tableCount = 0;
        //JsonString = '';
        //sqls = [];
      });
  };
  //启动后台服务
  var start = function () {

    var promise = $interval(function () {
      tableCount = DB_CONFIG.tables.length;
      DB_CONFIG.tables.forEach(function (table) {
        var columns = [];
        table.columns.forEach(function(column){
          if(column.name !='dr') {
            columns.push(column.name);
          }
        });
        var sql = 'select ' + columns.join(',') + ' from ' + table.name + ' where dr=0 and id not in ('+ids.join(',')+');;';
        tableCount--;
        DB.executeSql(sql, [], callback, table);
      });
    }, 60000);
    $rootScope.$on('$destroy',function(){
      $interval.cancel(promise);
    });
  };
  return {
    start: start
  };
});

